#!/usr/bin/env python
#

from xbmcswift2 import Plugin
from xbmcswift2 import xbmc

import bottlenose
import urllib
import resources.lib.api as apimod
import resources.lib.login as ll
import os

# TODO
# paging root still broken?
# login, launch vid, give control to vid
# find a way to actually use log in when launching to chrome (save cookies, extension)
# error handling amazon requests
# python packaging/modules
# movie list (genres, new releases, most popular, search)
# tv list (genres, new releases, most popular, search)
# watchlist (scraping?)
# add to library
# caching
# deal with getting the hierarchy efficiently (multiple bnodes?)
# mac support
# do i need to use plugin.finish()?
# clean up menu building
# clean up storage of genre and category nodes
# multi region
# logging - properly

# globals
#
plugin = Plugin()
plugin.log.setLevel('DEBUG')
api    = apimod.AIVApi(plugin)

osWin = xbmc.getCondVisibility('system.platform.windows')
osLinux = xbmc.getCondVisibility('system.platform.linux')
osOsx = xbmc.getCondVisibility('system.platform.osx')
pluginpath = plugin.addon.getAddonInfo('path')

# for debug xbmcswift2
if pluginpath == "Unavailable":
    pluginpath = "special://userdata/tmpcookies"
    COOKIEFILE = os.path.join(xbmc.translatePath(pluginpath))
else:
    COOKIEFILE = os.path.join(xbmc.translatePath(pluginpath),'resources','cache','cookies.lwp')

# menu
#
@plugin.route('/')
def show_root():
    menu = [
        {'label': _xl(30100), 'path':  plugin.url_for('show_watchlist')},
        {'label': _xl(30101), 'path':  plugin.url_for('show_category',category='movies')},
        {'label': _xl(30102), 'path':  plugin.url_for('show_category',category='tv')}
    ]
    return menu


@plugin.route('/watchlist')
def show_watchlist():
    menu = [
        {'label': _xl(30100)}
    ]
    return menu


@plugin.route('/categories/<category>')
def show_category(category):
    menu = [
        {'label': _xl(30110), 'path': plugin.url_for('show_new_root',category=category)},
        {'label': _xl(30111), 'path': plugin.url_for('show_popular_root',category=category)},
        {'label': _xl(30112), 'path': plugin.url_for('show_genres',category=category)},
        {'label': _xl(30113), 'path': plugin.url_for('show_search_root',category=category)},
    ]
    return menu


@plugin.route('/categories/<category>/genres')
def show_genres(category):

    menu = []
    genres = api._get_genres()

    for genre in sorted(genres.keys()):
        url=plugin.url_for('show_genre_root',
                           category=category,
                           genre=genre)
        menu.append({'label': genre, 'path': url})
    return menu


@plugin.route('/categories/<category>/new', name="show_new_root")
@plugin.route('/categories/<category>/new/page/<page>')
def show_new(category,page="0"):

    update_listing = (page != "0")
    page = "1" if page == "0" else page

    api_func = api.get_new
    api_args = (category,)

    url_func   = 'show_new'
    url_kwargs = { "category": category }

    menu = _make_paged_menu(api_func, api_args, url_func, url_kwargs, page)
    return plugin.finish(menu, update_listing=update_listing)


@plugin.route('/categories/<category>/popular', name="show_popular_root")
@plugin.route('/categories/<category>/popular/page/<page>')
def show_popular(category,page="0"):

    update_listing = (page != "0")
    page = "1" if page == "0" else page

    api_func = api.get_popular
    api_args = (category,)

    url_func   = 'show_popular'
    url_kwargs = { "category": category }

    menu = _make_paged_menu(api_func, api_args, url_func, url_kwargs, page)
    return plugin.finish(menu, update_listing=update_listing)


@plugin.route('/categories/<category>/search', name="show_search_root")
@plugin.route('/categories/<category>/search/<search_term>/page/<page>')
def show_search(category,search_term="",page="0"):

    if not search_term:
        search_term = plugin.keyboard(heading=_xl(30113))

    if search_term:
        plugin.log.info("Searching "+category+" for "+search_term)
    else:
        plugin.log.info("Empty searchterm")

    update_listing = (page != "0")
    page = "1" if page == "0" else page

    api_func = api.do_search
    api_args = (category,search_term)

    url_func   = 'show_search'
    url_kwargs = { "category":    category,
                   "search_term": search_term}

    menu = _make_paged_menu(api_func, api_args, url_func, url_kwargs, page)
    return plugin.finish(menu, update_listing=update_listing)


@plugin.route('/categories/<category>/genres/<genre>', name="show_genre_root")
@plugin.route('/categories/<category>/genres/<genre>/page/<page>')
def show_genre(category,genre,page="0"):

    update_listing = (page != "0")
    page = "1" if page == "0" else page

    api_func = api.get_genre
    api_args = (category,genre)

    url_func   = 'show_genre'
    url_kwargs = { "category": category,
                   "genre":    genre}

    menu = _make_paged_menu(api_func, api_args, url_func, url_kwargs, page)
    return plugin.finish(menu, update_listing=update_listing)


@plugin.route('/video/<asin>')
def play_video(asin):

    if not ll.do_login(COOKIEFILE,plugin):
        return plugin.url_for("show_root")

    xbmc.Player().stop()
    kiosk = "yes"
    url='http://www.amazon.co.uk/gp/product/'+asin+'/ref=dv_web_wtls_list_ovl_rs__wnzw'
    launcher="plugin.program.chrome.launcher/?url="+urllib.quote_plus(url)+"&mode=showSite&kiosk="+kiosk

    #xbmc.executebuiltin("RunPlugin("+launcher+")")

    #if osOsx:
    #    plugin.log.info("os is osx")
    #    try:
    #        xbmc.sleep(5000)
    #        subprocess.Popen('cliclick c:500,500', shell=True)
    #        subprocess.Popen('cliclick kp:arrow-up', shell=True)
    #        xbmc.sleep(5000)
    #        subprocess.Popen('cliclick c:500,500', shell=True)
    #        subprocess.Popen('cliclick kp:arrow-up', shell=True)
    #        xbmc.sleep(5000)
    #        subprocess.Popen('cliclick c:500,500', shell=True)
    #        subprocess.Popen('cliclick kp:arrow-up', shell=True)
    #    except:
    #        pass
    #elif osLinux:
    #    plugin.log.info("os is linux")
    #    try:
    #        xbmc.sleep(5000)
    #        subprocess.Popen('xdotool mousemove 9999 9999', shell=True)
    #        xbmc.sleep(5000)
    #        subprocess.Popen('xdotool mousemove 9999 9999', shell=True)
    #        xbmc.sleep(5000)
    #        subprocess.Popen('xdotool mousemove 9999 9999', shell=True)
    #    except:
    #        pass
    #else:
    #    plugin.log.info("os is win")

    plugin.log.info("Running "+launcher)
    return plugin.set_resolved_url("plugin://"+launcher)



# utils
#
def _xl(string_id):
    return plugin.get_string(string_id)


def _make_paged_menu(api_func, api_args, url_func, url_kwargs, page):

    plugin.log.debug("api_func:"+ str(api_func))
    plugin.log.debug("api_args:"+ str(api_args))
    plugin.log.debug("url_func:"+ str(url_func))
    plugin.log.debug("url_kwargs:"+ str(url_kwargs))
    plugin.log.debug("page:"+ str(page))

    items, next_page = api_func(*api_args,page=page)

    menu = []
    page = int(page)

    for item in items:
        menu.append({'label':       item['title'],
                     'path':        plugin.url_for('play_video', asin=item['asin']),
                     'is_playable': True})

    url_kwargs['endpoint'] = url_func

    if next_page:
        url_kwargs['page'] = str(page+1)
        menu.insert(0, {
            'label': _xl(30120)+' >>',
            'path':  plugin.url_for(**url_kwargs)
        })

    if page > 1:
        url_kwargs['page'] = str(page-1)
        menu.insert(0, {
            'label': '<< '+_xl(30121),
            'path':  plugin.url_for(**url_kwargs)
        })

    return menu


# main
#
if __name__ == '__main__':
    plugin.run()
